package com.ujs.edu.demo.controller;

import com.ujs.edu.demo.config.NeedLogin;
import com.ujs.edu.demo.dao.BcAdminMapper;
import com.ujs.edu.demo.dataobject.BcAdmin;
import com.ujs.edu.demo.util.MSUtil;
import com.ujs.edu.demo.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpSession;

@Controller
public class PersonController {

    @Autowired
    private BcAdminMapper bcAdminMapper;

    //显示个人中心页面，并加载信息

    @RequestMapping(path = "person")
    public ModelAndView person(@SessionAttribute("bcAdmin") BcAdmin bcAdmin){
        ModelAndView view=new ModelAndView();

        BcAdmin bcAdmin1=bcAdminMapper.selectByPrimaryKey(bcAdmin.getAdminId());
        view.addObject("admin",bcAdmin1);
        view.setViewName("person");
        return view;
    }

    //完善信息
    @RequestMapping(path = "/personUpdate")
    public RedirectView updatePerson(BcAdmin bcAdmin, @SessionAttribute("bcAdmin") BcAdmin bcAdmin1){
        bcAdmin.setAdminId(bcAdmin1.getAdminId());
        bcAdminMapper.updateByPrimaryKey(bcAdmin);
        RedirectView view=new RedirectView();
        view.setUrl("/person");
        return view;
    }

    //更新密码
    @RequestMapping(path = "/updatePassword")
    public RedirectView updatePassword(@RequestParam("oldpassword") String oldpassword,
                                       @RequestParam("newpassword")String newpassword,
                                       @RequestParam("check") String check,
                                       @SessionAttribute("bcAdmin") BcAdmin bcadmin) throws Exception {
        RedirectView view=new RedirectView();
        BcAdmin bcAdmin=bcAdminMapper.selectPassword(bcadmin.getAdminId());
        view.setUrl("/person");
        if (!MSUtil.md5(oldpassword,"xhj").equals(bcAdmin.getPassword())){
            return view;
        }else {
          if (newpassword.equals(check)){
              String newpassword1=MSUtil.md5(check,"xhj");
              bcadmin.setPassword(newpassword1);
              int a=bcAdminMapper.updatePassword(bcadmin);
          }
        }
        return view;
    }
}
